<!--
  * 111
  *
  * @Author:    zxp
  * @Date:      2024-09-27 09:37:05
  * @Copyright  11111
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="tiaozhuan">
          <template #icon>
            <PlusOutlined/>
          </template>
          新建
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <!---------- 表格操作行 end ----------->
    <div class="smart-table-setting-block">
      <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.DATASOURCE.SOURCE_MANAGER"
                     :refresh="queryData"/>
    </div>
    <!---------- 表格 begin ----------->
    <a-table
        size="small"
        :dataSource="data.tableData"
        :columns="columns"
        :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
    >
      <template #bodyCell="{text,record, column }">
        <template v-if="column.dataIndex === 'dataSourceType'">
          <a-tag color="cyan">
            {{ text && text.length > 0 ? text.map((e) => e.valueName).join(',') : '暂无' }}
          </a-tag>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
<!--            <a-button type="link" @click="tiaozhuan(record)">配置</a-button>-->
            <a-button type="link" @click="tiaozhuan1(record.dataSourceId)">内容配置</a-button>
            <a-button type="link" @click="tiaozhuan(record)">数据源配置</a-button>
            <a-button @click="onDelete(record)" danger type="link">删除</a-button>
            <a-button @click="sendPrimaryKey(record.dataSourceId)" type="link">创建任务</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="queryData"
          @showSizeChange="queryData"
          :show-total="(total) => `共${total}条`"
      />
    </div>

    <DatasourceForm ref="formRef" @reloadList="queryData"/>

  </a-card>
  <SelectFieldsList ref="selectFieldsRef" @on-exit="exit"/>


</template>
<script setup>
import {reactive, ref, onMounted, computed, onUpdated, defineEmits} from 'vue';
import {message, Modal} from 'ant-design-vue';
import {SmartLoading} from '/@/components/framework/smart-loading';
import {datasourceApi} from '/@/api/business/super-computer/datasource/datasource-api.js';
import {PAGE_SIZE_OPTIONS} from '/@/constants/common-const';
import {smartSentry} from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';
import DatasourceForm from './datasource-form.vue';
import {useRouter} from "vue-router";
import {datataskApi} from "/@/api/business/super-computer/datatask/datatask-api.js";
import {TABLE_ID_CONST} from "/@/constants/support/table-id-const.js";
import AdModal from "/@/views/system/home/ad-modal.vue";
import SelectFieldsList from "/@/views/business/super-computer/select-fields/select-fields-list.vue";
//import FilePreview from '/@/components/support/file-preview/index.vue'; // 图片预览组件

// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '数据源类型',
    dataIndex: 'dataSourceType',
    ellipsis: true,
  },
  {
    title: '数据源名称',
    dataIndex: 'dataSourceName',
    ellipsis: true,
  },
  {
    title: '连接信息',
    dataIndex: 'connInformation',
    ellipsis: true,
  },
  {
    title: '源表名',
    dataIndex: 'sourceTablename',
    ellipsis: true,
  },
  {
    title: '源字段',
    dataIndex: 'sourceColumns',
    ellipsis: true,
  },
  {
    title: '修改时间',
    dataIndex: 'updateTime',
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    ellipsis: true,
  },
  {
    title: '创建人',
    dataIndex: 'createUser',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 90,
  },
]);

// ---------------------------- 查询数据表单和方法 ----------------------------

const queryFormState = {
  pageNum: 1,
  pageSize: 10,
};
// 查询表单form
const queryForm = reactive({...queryFormState});
// 表格加载loading
const tableLoading = ref(false);
// 表格数据
const data = reactive({
  tableData: [],
  index: null,
  total: null
})
// 总数
const total = ref(0);

// 重置查询条件
function resetQuery() {
  let pageSize = queryForm.pageSize;
  Object.assign(queryForm, queryFormState);
  queryForm.pageSize = pageSize;
  queryData();
}

// 查询数据
async function queryData() {
  tableLoading.value = true;
  try {
    let queryResult = await datasourceApi.queryPage(queryForm);
    data.tableData = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}
const emits = defineEmits(['reloadList']);

function exit() {
  queryData()
}

onMounted(queryData);

function truncate(text, length) {
  if (text.length > length) {
    return text.substring(0, length) + '...';
  }
  return text
}

const router = useRouter();

function tiaozhuan(data) {
  // console.log(data);
  formRef.value.show(data);
}
const selectFieldsRef = ref()

async function tiaozhuan1(data) {
  // console.log(data);
  await selectFieldsRef.value.showSelectFieldsModal(data);

}


// ---------------------------- 添加/修改 ----------------------------
const formRef = ref();


// ---------------------------- 单个删除 ----------------------------
//确认删除
function onDelete(data) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestDelete(data);
    },
    cancelText: '取消',
    onCancel() {
    },
  });
}

//请求删除
async function requestDelete(data) {
  SmartLoading.show();
  try {
    let deleteForm = {
      goodsIdList: selectedRowKeyList.value,
    };
    await datasourceApi.delete(data.dataSourceId);
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

// ---------------------------- 批量删除 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}

// 批量删除
function confirmBatchDelete() {
  Modal.confirm({
    title: '提示',
    content: '确定要批量删除这些数据吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestBatchDelete();
    },
    cancelText: '取消',
    onCancel() {
    },
  });
}

//请求批量删除
async function requestBatchDelete() {
  try {
    SmartLoading.show();
    await datasourceApi.batchDelete(selectedRowKeyList.value);
    message.success('删除成功');
    await queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

//创建任务
function sendPrimaryKey(primaryKey) {
  if (primaryKey === null) {
    message.error("数据源Id为空")
    return;
  }
  try {
    datataskApi.addTask(primaryKey);
    message.success("任务添加成功, 请在传输任务管理中查看")
  } catch (e) {
    message.error("信息发送失败")
    smartSentry.captureError(e)
  }
}

</script>

<style scoped>

</style>
